package com.example.a828502.filereadandwritetest;

import android.app.ListActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class MainActivity extends AppCompatActivity {

    private EditText editor = null;
    private TextView textShow;
    private ListView listView;
    private static String NOTES="notes.txt";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editor = (EditText)findViewById(R.id.c23_editor);
        textShow = (TextView)findViewById(R.id.textshow);
        Button button = (Button)findViewById(R.id.c23_close);
        Button saveButton = (Button)findViewById(R.id.save);
        Button readButton = (Button)findViewById(R.id.read);
        Button readXml = (Button)findViewById(R.id.readXml);
        listView = (ListView) findViewById(R.id.listView);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveFile();
            }
        });
        readButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readFile();
            }
        });

        readXml.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readXmlFile();
            }
        });
    }
    public void saveFile(){
        try{
            /* openFileOutput (String  name, int mode)中mode是打开模式，0或者MODE_PRIVATE为缺省模式， MODE_APPEND表示在文件后增加，MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE是控制权限  */
            OutputStreamWriter out = new OutputStreamWriter(openFileOutput(NOTES, 0));
            out.write(editor.getText().toString());
            out.close();
        }catch(Throwable t){
            Toast.makeText(MainActivity.this, "Exception: " + t.toString(), Toast.LENGTH_SHORT).show();

        }
    }

    public void readFile(){
        try{
            /* openFileInput( String name)是android.content.ContextWrapper类的函数，可以在activity中直接调用，参数name，不能包含目录分割符，即只能处理应用私有文件夹文件，获得InputStream后，按常规java处理。如果需要访问更多的地方，需要创建content privider，在以后学习*/
            InputStream in = openFileInput(NOTES);
            if(in != null){
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String str;
                StringBuffer buf = new StringBuffer();
                while(( str = reader.readLine()) != null){
                    buf.append(str + "\n");
                }
                in.close();
                textShow.setText(buf.toString());
            }
        }catch(Throwable t){
            Toast.makeText(MainActivity.this, "Exception: " + t.toString(), Toast.LENGTH_SHORT).show();

        }
    }
    public void readXmlFile(){
         ArrayList<String> items = new ArrayList<String>();
        try{
            // 获取该文件的InputStream，首先通过getResrouces()获取资源对象，然后通过openRawResource()获取指定文件的InputStream  
            InputStream in = getResources().openRawResource(R.raw.strings);
            //解释XML文件：从中获取数据，放入ArrayList中。建立XML解析，将InputStream放入DOM文件中，通过树状结构NodeList获取所需的数据。  
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(in,null);
            NodeList words = doc.getElementsByTagName("word");

            for(int i = 0; i < words.getLength(); i ++){
                Element node = (Element)words.item(i);
                items.add(node.getAttribute("value"));
            }
        }catch(Throwable t){
            Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
        }

        ArrayAdapter adapter
                = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
        listView.setAdapter(adapter);

    }

    protected void onResume() {
        super.onResume();
        try{
            /* openFileInput( String name)是android.content.ContextWrapper类的函数，可以在activity中直接调用，参数name，不能包含目录分割符，即只能处理应用私有文件夹文件，获得InputStream后，按常规java处理。如果需要访问更多的地方，需要创建content privider，在以后学习*/
            InputStream in = openFileInput(NOTES);
            if(in != null){
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String str;
                StringBuffer buf = new StringBuffer();
                while(( str = reader.readLine()) != null){
                    buf.append(str + "\n");
                }
                in.close();
                textShow.setText(buf.toString());
            }
        }catch(Throwable t){
            Toast.makeText(MainActivity.this, "Exception: " + t.toString(), Toast.LENGTH_SHORT).show();

        }

    }
    protected void onPause() {
        super.onPause();
        try{
            /* openFileOutput (String  name, int mode)中mode是打开模式，0或者MODE_PRIVATE为缺省模式， MODE_APPEND表示在文件后增加，MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE是控制权限  */
            OutputStreamWriter out = new OutputStreamWriter(openFileOutput(NOTES, 0));
            out.write(editor.getText().toString());
            out.close();
        }catch(Throwable t){
            Toast.makeText(MainActivity.this, "Exception: " + t.toString(), Toast.LENGTH_SHORT).show();

        }
    }

//    public void setListAdapter(ArrayAdapter<String> listAdapter) {
//        this.listAdapter = listAdapter;
//    }
}
